<?php

/*
采购订单列表
*/
namespace Modules\Purchasing\Http\Repositories;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Modules\Purchasing\Models\Supplier;
use Modules\Purchasing\Models\Supplierschedule;
use Illuminate\Support\Facades\DB;
use Catch\Exceptions\FailedException;
use Modules\Base\Service\BoxService;
use Modules\Purchasing\Models\Suppliernamedelivery;
use Modules\Purchasing\Models\Purchaseorder;
use Modules\Purchasing\Models\Purchaseorderschedule;
use App\Enums\BoxFrom;
use Modules\Purchasing\Models\Provisionalschedule;
use Modules\Purchasing\Models\Barcodeprinting;

class SupplierReget
{
    /*
    数据列表
    */
    public static function list($data = [])
    {
        return self::getBuilder($data)->paginate($data['limit'] ?? 20);
    }


     /**
     *查询列表
     *
     * @param array $data
     * @return Builder
     */
    public static function getBuilder(array $data = []): Builder
    {
      
       
        $builder = Supplier::query()->with('detailscheckAll');
        if (isset($data['supplierOrder'])) {
            $builder->where('supplierOrder', 'like', "%{$data['supplierOrder']}%");
        }
        if (isset($data['remarks'])) {
            $builder->where('remarks', 'like', "%{$data['remarks']}%");
        }

        if (isset($data['state'])) {
            $builder->where('state',$data['state']);
        }
        
        if (isset($data['creator_id'])) {
            $builder->where('creator_id',$data['creator_id']);
        }
        
        if (isset($data['temporary'])) {
             //已暂收
            // $Provisionalschedule = Provisionalschedule::select('supplier_id')->get()->toArray();
            // foreach ($Provisionalschedule as $k=>$v){
            //      Supplier::select('id')->where('id',$v['supplier_id'])->update(['temporary'=>1]);
            // }
            $builder->where('temporary',$data['temporary']);
            
        }
        
        


        // 采购订单号
        if (isset($data['fbillno'])) {
            $res = Purchaseorder::select('id')->where('fbillno', 'like', "%{$data['fbillno']}%")
            //->join('purchaseorderschedule as purchaseorderschedule', 'purchaseorderschedule.purchaseorder_id', '=', 'purchaseorder.id')
            ->get()
            ->toArray();
            $purchaseorder_id = [];
            foreach($res as $k=>$v){
                $purchaseorder_id[] = $v['id'];
            }
            $purchaseorder_id = array_unique($purchaseorder_id);
             $resdata = Supplierschedule::select('supplier_id')
             ->whereIn('purchaseorder_id',$purchaseorder_id)
             ->get()
             ->toArray();

             $supplier_id = [];
             foreach($resdata as $k=>$v){
                $supplier_id[] = $v['supplier_id'];
             }
             $builder->whereIn('id',$supplier_id);

        }

          // 采购订组织
          if (isset($data['fpurchaseorgid_name'])) {

            $res = Purchaseorder::select('id')->where('fpurchaseorgid_name', 'like', "%{$data['fpurchaseorgid_name']}%")
            //->join('purchaseorderschedule as purchaseorderschedule', 'purchaseorderschedule.purchaseorder_id', '=', 'purchaseorder.id')
            ->get()
            ->toArray();
            $purchaseorder_id = [];
            foreach($res as $k=>$v){
                $purchaseorder_id[] = $v['id'];
            }

             $resdata = Supplierschedule::select('supplier_id')
             ->whereIn('purchaseorder_id',$purchaseorder_id)
             ->get()
             ->toArray();

             $supplier_id = [];
             foreach($resdata as $k=>$v){
                $supplier_id[] = $v['supplier_id'];
             }
             $builder->whereIn('id',$supplier_id);

        }

        
        $builder->orderBy('id', 'desc');
        return $builder;
    }

        /*
    数据列表
    */
    public static function listTwo($data = [])
    {
        return self::getBuilderTwo($data)->paginate($data['limit'] ?? 20);
    }
      /**
     *查询列表
     *
     * @param array $data
     * @return Builder
     */
    public static function getBuilderTwo(array $data = []): Builder
    {
      
       
        $builder = Barcodeprinting::query();
        // if (isset($data['supplierOrder'])) {
            // $builder->where('supplierOrder', 'like', "%{$data['supplierOrder']}%");
        // }
        if (isset($data['supplier_id'])) {
            $builder->where('supplier_id',$data['supplier_id']);
        }

        $builder->orderBy('id', 'desc');
        return $builder;
    }


    /*
    数据添加方法
    */
    public static function create(array $data)
    {
        
        $Supplier = new Supplier;
        return self::createOrSave($Supplier, $data);
    }

    //数据添加方法
    public static function createOrSave(Supplier $Supplier,$data)
    {
        foreach($data['detailscheck_all'] as $k=>$v){
            $send_quantity = Purchaseorderschedule::select('fmaterialid','fmaterialname','send_quantity','fqty','id')
            ->where('id',$v['purchaseorderschedule_id'])
            ->where('purchaseorder_id',$v['purchaseorder_id'])
            ->first();
            if(empty($send_quantity)) throw new FailedException('数据出错，无法找到物料数据');

            //  $sl = $send_quantity->send_quantity + $v['quantity'];
            //  if($sl > $send_quantity->fqty){
            //      throw new FailedException('已做单的送货数量超过采购数量，无法做单');
            //  }

         }

        // $data = [
        //     'remarks'=>'备注',
        //     'state'=>1,
        //     'creator_id'=>$data['creator_id'],
        //     'mix_quantity'=>2,
        //     'fcl_quantity'=>3,
        // ];
        try {
            //开始起事务
            DB::beginTransaction();
            $SupplierData = [];
            // $SupplierData['supplierOrder'] = 'GYSH'.date('Ymd',time()).'-'.makeSerial();
            $SupplierData['supplierOrder'] = \App\Services\UnitService::createDocno(\App\Enums\OrderNoPrefix::NO_GYSH->value);
            
            $SupplierData['remarks'] = $data['remarks'];
            // $SupplierData['state'] = $data['state'];
            // $SupplierData['mix_quantity'] = $data['mix_quantity'];
            // $SupplierData['fcl_quantity'] = $data['fcl_quantity'];
            $SupplierData['creator_id'] = $data['creator_id'];
            $Supplier->fill($SupplierData);
            $Supplier->save();
            
            // $data['detailscheckAll'] = [
            //     [
            //         'purchaseorder_id'=>1,
            //         'quantity'=>1,
            //         'deliverydate'=>'2023-05-24',
            //         // 'numberof'=>10,
            //         'typebox'=>1,
            //         'fseq'=>1,
            //     ],
            //     [
            //         'purchaseorder_id'=>1,
            //         'quantity'=>1,
            //         'deliverydate'=>'2023-05-24',
            //         // 'numberof'=>10,
            //         'typebox'=>0,
            //         'fseq'=>1,
            //     ],
            //     [
            //         'purchaseorder_id'=>1,
            //         'quantity'=>1,
            //         'deliverydate'=>'2023-05-24',
            //         // 'numberof'=>10,
            //         'typebox'=>0,
            //         'fseq'=>2,
            //     ]
            // ];

            $Supplier->detailscheckAll()->createMany( $data['detailscheck_all'] );
            //修改采购订单为已做单情况
            foreach($data['detailscheck_all'] as $k=>$v){

               $send_quantity = Purchaseorderschedule::select('fmaterialid','fmaterialname','send_quantity','fqty','id')
               ->where('id',$v['purchaseorderschedule_id'])
               ->where('purchaseorder_id',$v['purchaseorder_id'])
               ->first();
               if(empty($send_quantity)) throw new FailedException('数据出错，无法找到物料数据');
               $sl = $send_quantity->send_quantity + $v['quantity'];
                // if($sl > $send_quantity->fqty){
                //     throw new FailedException('送货数量超过采购数量，无法做单');
                // }
                
                $data = [];
                if($sl == $send_quantity->fqty){
                    $data['state'] = 1;
                    // Purchaseorderschedule::where('id',$send_quantity->id)->update(['state'=>1]);
                }
                    $data['send_quantity'] = $sl;
                    Purchaseorderschedule::where('id',$send_quantity->id)->update($data);

            }
            
            // $name = [];
            // foreach($data['detailscheck_all'] as $k=>$v){
            //     $name[$v['purchaseorderschedule_id']] = $v['purchaseorder_id'];
            // }
            // $SuppliernamedeliveryAll = [];
            // $i = 0;
            // foreach($name as $k=>$v){
            //     $SuppliernamedeliveryAll[$i]['purchaseorderschedule_id'] = $k;
            //     // $SuppliernamedeliveryAll[$i]['supplier_id'] = $Supplier['id'];
            //     $i++;
            // }
        
            // $Supplier->SuppliernamedeliveryAll()->delete();
            // $Supplier->()SuppliernamedeliveryAll->createMany( $SuppliernamedeliveryAll );
            DB::commit();
            return $Supplier['id'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('数据添加失败，服务器上火星了请联系技术处理');
        }
    }

    //修改
    public static function createUpdate($id,$data)
    {
        foreach($data['detailscheck_all'] as $k=>$v){
            $send_quantity = Purchaseorderschedule::select('fmaterialid','fmaterialname','send_quantity','fqty','id')
            ->where('id',$v['purchaseorderschedule_id'])
            ->where('purchaseorder_id',$v['purchaseorder_id'])
            ->first();

            if(empty($send_quantity)) throw new FailedException('数据出错，无法找到物料数据');

             $sl = $send_quantity->send_quantity + $v['quantity'];

            //  if($sl > $send_quantity->fqty){
            //      throw new FailedException('已做单的送货数量超过采购数量，无法做单');
            //  }
         }

         

        try {
            //开始起事务
            DB::beginTransaction();
            $Supplierschedule = Supplierschedule::where('supplier_id',$id)->get()->toArray();


              //修改原来的之前的
              foreach($Supplierschedule as $k=>$v){
                $send_quantity = Purchaseorderschedule::select('fmaterialid','fmaterialname','send_quantity','fqty','id')
                ->where('id',$v['purchaseorderschedule_id'])
                ->where('purchaseorder_id',$v['purchaseorder_id'])
                ->first();

                if(empty($send_quantity)) throw new FailedException('数据出错，无法找到物料数据');
                 $sl = $send_quantity->send_quantity - $v['quantity'];

                //  if($sl > $send_quantity->fqty){
                //      throw new FailedException('送货数量超过采购数量，无法做单');
                //  }

                $datares = [];
                if($sl == $send_quantity->fqty){
                    $datares['state'] = 1;
                    // Purchaseorderschedule::where('id',$send_quantity->id)->update(['state'=>1]);
                }
                    $datares['send_quantity'] = $sl;
                    Purchaseorderschedule::where('id',$send_quantity->id)->update($datares);

             }


            $Supplier = Supplier::query()->updateOrCreate(['id' => $id], [
                'modifier'       => $data['modifier']  ?? '',
                'remarks'       => $data['remarks']  ?? '',
                // 'mix_quantity'       => $data['mix_quantity']  ?? '',
                // 'fcl_quantity'       => $data['fcl_quantity']  ?? '',
            ]);
          
            Supplierschedule::where('supplier_id',$id)->delete();
            
            $Supplier->detailscheckAll()->createMany( $data['detailscheck_all'] );

            
            //修改采购订单为已做单情况
            foreach($data['detailscheck_all'] as $k=>$v){
                $send_quantity = Purchaseorderschedule::select('fmaterialid','fmaterialname','send_quantity','fqty','id')
                ->where('id',$v['purchaseorderschedule_id'])
                ->where('purchaseorder_id',$v['purchaseorder_id'])
                ->first();

                if(empty($send_quantity)) throw new FailedException('数据出错，无法找到物料数据');

                 $sl = $send_quantity->send_quantity + $v['quantity'];

                //  if($sl > $send_quantity->fqty){
                //      throw new FailedException('送货数量超过采购数量，无法做单');
                //  }

                 $datarestwo = [];
                if($sl == $send_quantity->fqty){
                    $datarestwo['state'] = 1;
                    // Purchaseorderschedule::where('id',$send_quantity->id)->update(['state'=>1]);
                }
                    $datarestwo['send_quantity'] = $sl;
                    Purchaseorderschedule::where('id',$send_quantity->id)->update($datarestwo);

             }

            // Suppliernamedelivery::where('supplier_id',$id)->delete();
            
            // $Supplier->SuppliernamedeliveryAll()->delete();
            // $name = [];
            // foreach($data['detailscheck_all'] as $k=>$v){
            //   $purchaseorderschedule_id =  Suppliernamedelivery::where('purchaseorderschedule_id',$v['purchaseorderschedule_id'])->first();
            //   if(empty($purchaseorderschedule_id)){
            //      throw new FailedException('品号数据没有生成无法录入,请先生成品号数据录入箱数。');
            //      return; 
            //   }
            //     // $name[$v['purchaseorderschedule_id']] = $v['purchaseorder_id'];
            // }
            
            // $SuppliernamedeliveryAll = [];
            // $i = 0;
            // foreach($name as $k=>$v){
            //     $SuppliernamedeliveryAll[$i]['purchaseorderschedule_id'] = $k;
            //     $i++;
            // }

            // $Supplier->SuppliernamedeliveryAll()->createMany($data['SuppliernamedeliveryAll']);
            
            DB::commit();
            return '修改成功';
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('数据修改失败，服务器上火星了请联系技术处理');
        }
    }

    
    /**
     * 审核后修改 实际到货货箱数
     *
     */
    public static function modifydata($data)
    {
        try {
            //开始起事务
            DB::beginTransaction();
            foreach($data as $k=>$v){
                Supplierschedule::where('id',$v['id'])->update([
                    'actual_number'=>$v['actual_number']
                ]);
            }
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('修改失败');
        }
       
      
    }

    /**
     * 查询一条数据
     *
     */
    public static function find($id)
    {
        return Supplier::query()->with('detailscheckAll')->find($id);
    }

    /**
     * @param $id
     * @return void
     */
    public static function delete($id)
    {
       
        try {
            //开始起事务
            DB::beginTransaction();
                
                $data = Supplierschedule::query()->where('supplier_id',$id)->get()->toArray();

                foreach($data as $k=>$v){

                        $send_quantity = Purchaseorderschedule::select('fmaterialid','fmaterialname','send_quantity','fqty','id')
                        ->where('id',$v['purchaseorderschedule_id'])
                        ->first();
                        if(empty($send_quantity)) throw new FailedException('数据出错，无法找到物料数据');
                        $sl = $send_quantity->send_quantity - $v['quantity'];
                        if($sl < 0){
                            throw new FailedException('系统出错');
                        }
                        Purchaseorderschedule::where('id',$send_quantity->id)->update([
                            'send_quantity'=>$sl,
                            'state'=>0,
                        ]);
                }

                Supplier::query()->where('id',$id)->delete();
                Supplierschedule::query()->where('supplier_id',$id)->delete();
                //Suppliernamedelivery::query()->where('supplier_id',$id)->delete();
            DB::commit();
            return '删除成功';
        } catch (\Exception $e) {
            DB::rollBack();
             throw new FailedException('系统出错');
        }


    }
     /**审核接口
     * @param $id
     * @return void
     */
    public static function auditupdate($id,$data)
    {
       
        $resdata = Supplierschedule::select('supplier_id','purchaseorderschedule_id','number','id')->where('supplier_id',$id)->get();
        foreach($resdata as $k=>$v){
            if(empty($v['number'])){
                return throw new FailedException('无法审核有的品号箱号未录入');
            }
        }
            
  
       
        try {
            //开始起事务
            DB::beginTransaction();
           
    
             $Supplier = Supplier::query()->updateOrCreate(['id' => $id], [
                'state'       => 1,
                'modifier'       => $data['modifier']  ?? '',
            ]);

            foreach($resdata as $k=>$v){

                if(empty($v['number'])){
                    return $data=['code'=>10005,'message'=>'无法审核有的品号箱号未录入'];
                //  return throw new FailedException('无法审核有的品号箱号未录入');
                }else{
     
                    $daju =Purchaseorderschedule::select('purchaseorderschedule.fmaterialid','purchaseorder.fbillno','purchaseorder.fpurchaseorgid_number','purchaseorder.id','purchaseorder.fsupplierid_number')
                    ->join('purchaseorder as purchaseorder', 'purchaseorder.id', '=', 'purchaseorderschedule.purchaseorder_id')
                    ->where('purchaseorderschedule.id',$v['purchaseorderschedule_id'])
                    // ->where('purchaseorderschedule.purchaseorder_id',$v['purchaseorder_id'])
                    ->first();
                    $Bacode = BoxService::makeBoxNumber(
                        $v['number'],
                        BoxFrom::PURCHASE_ORDER->value,
                        0,
                        $daju->fsupplierid_number,
                        $daju->fbillno,
                        $daju->fmaterialid
                    );
                    // $Bacode = BoxService::makeBoxNumber($data['modifier'],$v['number'],2,$v['supplier_id']);
                    $mix = [];
                    foreach($Bacode as $ks=>$vs){
                        $mix[$ks]['barcode'] = $vs;
                        $mix[$ks]['creator_id'] = $data['modifier'];
                        $mix[$ks]['purchaseorderschedule_id'] = $v['purchaseorderschedule_id'];
                        $mix[$ks]['supplierschedule_id'] = $v['id'];
                    }
                    $Supplier->BarcodeprintingAll()->createMany($mix);
                    
                }
            }
            
            
            //混合
            // $FCL = [];
            // $mix = [];
            // if($Supplier['mix_quantity']!==0&&!empty($Supplier['mix_quantity'])){
            //     $Bacode = BoxService::makeBoxNumber($data['modifier'],$data['mix_quantity']);
            //     $mix = [];
            //     foreach($Bacode as $k=>$v){
            //         $mix[$k]['barcode'] = $v;
            //         $mix[$k]['creator_id'] = $data['modifier'];
            //         $mix[$k]['typebox'] = 0;
            //     }
            // }

            // //整箱
            // if($Supplier['fcl_quantity']!==0&&!empty($Supplier['fcl_quantity'])){
            //     $Bacode = BoxService::makeBoxNumber($data['modifier'],$data['fcl_quantity']);
            //     foreach($Bacode as $k=>$v){
            //         $FCL[$k]['barcode'] = $v;
            //         $FCL[$k]['creator_id'] = $data['modifier'];
            //         $FCL[$k]['typebox'] = 1;
            //     }
            // }
            // $barcodeData = array_merge($mix,$FCL);
            // $Supplier->BarcodeprintingAll()->createMany($barcodeData);

            DB::commit();
            return $data=['code'=>1000,'message'=>'审核成功'];

        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException($e);
        }


    }


    /**生成品名数据
     * @param $id
     * @return void
     */
    // public static function PostcategoryData($data)
    // {
       
    //     try {
    //         //开始起事务
    //         DB::beginTransaction();
    //         $Suppliernamedelivery = new Suppliernamedelivery;
    //         $Suppliernamedelivery->fill($data);
    //         $Suppliernamedelivery->save();
    //         DB::commit();
    //         return '删除成功';
    //     } catch (\Exception $e) {
    //         DB::rollBack();
    //         throw new FailedException('系统出错请联系技术处理');
    //     }

    // }
     /**品名修改接口
     * @param $id
     * @return void
     */
    // public static function PostcategoryDatamodify($id,$data)
    // {
       
    //     try {
    //         //开始起事务
    //         DB::beginTransaction();
    //         $Supplier = Supplier::query()->updateOrCreate(['id' => $id], [
    //             'modifier'       => $data['modifier']  ?? '',
    //         ]);

    //         Suppliernamedelivery::where('supplier_id',$id)->delete();
    //         $Supplier->SuppliernamedeliveryAll()->createMany( $data );
           
    //         DB::commit();
    //         return '删除成功';
    //     } catch (\Exception $e) {
    //         DB::rollBack();
    //         throw new FailedException('系统出错请联系技术处理');
    //     }


    // }




}
